package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.ForgetPassworVersionCodeDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.SubmitChangePasswordBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 21.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 *
 * @desc 忘记密码
 */
public class ForgetPasswordActivity extends Activity {

    private static final String TAG ="ForgetPasswordActivity" ;
    @Bind(R.id.activity_forget_password_iv_return)
    ImageView activityForgetPasswordIvReturn;
    @Bind(R.id.activity_forget_password_rl_title)
    RelativeLayout activityForgetPasswordRlTitle;
    @Bind(R.id.activity_forget_password_et_phone_number)
    EditText activityForgetPasswordEtPhoneNumber;
    @Bind(R.id.activity_forget_password_et_verification_code)
    EditText activityForgetPasswordEtVerificationCode;
    @Bind(R.id.activity_forget_password_tv_send_verification_code)
    TextView activityForgetPasswordTvSendVerificationCode;
    @Bind(R.id.activity_forget_password_ll_input)
    LinearLayout activityForgetPasswordLlInput;
    @Bind(R.id.activity_forget_password_rl_next_step)
    RelativeLayout activityForgetPasswordRlNextStep;

    @Bind(R.id.activity_login_et_new_password)
    EditText activityForgetPasswordEtNewPassword;


    private int i = RBConstants.COUNTDOWN;
    private Timer timer = null;
    private TimerTask task = null;
    private Handler mhandler = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        ButterKnife.bind(this);

        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);


    }

    @OnClick({R.id.activity_forget_password_iv_return, R.id.activity_forget_password_tv_send_verification_code, R.id.activity_forget_password_rl_next_step})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_forget_password_iv_return:
                Intent intent = new Intent(ForgetPasswordActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.activity_forget_password_tv_send_verification_code:
               String  PhoneNumber =  activityForgetPasswordEtPhoneNumber.getText().toString().trim();
                if(!TextUtils.isEmpty(PhoneNumber)){
                    String  TvSendVerificationCode =  activityForgetPasswordTvSendVerificationCode.getText().toString().trim();
                    if(TvSendVerificationCode.equals("发送验证码")){
                        SendVersionCodeDate(PhoneNumber);
                        countdown(); //倒计时
                    }else{
                        Toast.makeText(this,"不能点多次",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this,"请先输入手机号",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.activity_forget_password_rl_next_step:
                String  PhoneNumber_01 =  activityForgetPasswordEtPhoneNumber.getText().toString().trim();
                if(!TextUtils.isEmpty(PhoneNumber_01)){
                    String  TvSendVerificationCode =  activityForgetPasswordTvSendVerificationCode.getText().toString().trim();
                    if(!TextUtils.isEmpty(TvSendVerificationCode)){
                        String  EtNewPassword  =  activityForgetPasswordEtNewPassword.getText().toString().trim();
                        if(!TextUtils.isEmpty(EtNewPassword)){
                            submitNextStep(PhoneNumber_01,TvSendVerificationCode,EtNewPassword);
                        }else{
                            Toast.makeText(this,"请先输入新密码",Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(this,"请先输入验证码",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this,"请先输入手机号",Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }
    /**
     * @DESC 提交修改密码
     * @param phoneNumber_01 手机号
     * @param tvSendVerificationCode 验证码
     * @param etNewPassword  新密码
     * */
    private void submitNextStep(String phoneNumber_01, String tvSendVerificationCode, String etNewPassword) {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.SUBMIT_CHANGE_PASSWORD)
                .addParams("tel",phoneNumber_01)
                .addParams("password", etNewPassword)
                .addParams("code", tvSendVerificationCode)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                        Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final SubmitChangePasswordBean submitChangePasswordBean =   gson.fromJson(parseNetworkResponse,SubmitChangePasswordBean.class);
                        if(submitChangePasswordBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ForgetPasswordActivity.this,"密码修改成功",Toast.LENGTH_SHORT).show();

                                    Intent intent = new Intent(ForgetPasswordActivity.this,LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ForgetPasswordActivity.this,submitChangePasswordBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 发送验证码
     * @param phoneNumber 手机号
     * */
    private void SendVersionCodeDate(String phoneNumber) {
        OkHttpUtils
                .get()
                .url(RBConstants.SERVER_URL+RBConstants.FORGET_PASSWORD_SEND_VERSION_CODE) //FORGET_PASSWORD_SEND_VERSION_CODE
                .addParams("tel", phoneNumber)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                       // Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final ForgetPassworVersionCodeDateBean forgetPassworVersionCodeDateBean =   gson.fromJson(parseNetworkResponse, ForgetPassworVersionCodeDateBean.class);
                        if(forgetPassworVersionCodeDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ForgetPasswordActivity.this,forgetPassworVersionCodeDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                    SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("phone_number",forgetPassworVersionCodeDateBean.data);
                                    edit.commit();
                                   // finish();
                                    //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ForgetPasswordActivity.this,forgetPassworVersionCodeDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    //倒计时
    private void countdown() {
        startTime();
    }
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            if(i>0){
                activityForgetPasswordTvSendVerificationCode.setText("重新发送"+i+"s");
                startTime();
            }else{
                stopTime();
                activityForgetPasswordTvSendVerificationCode.setText("发送验证码");
                i = 60 ;

            }

        };
    };

    public void startTime(){
        timer = new Timer();
        task = new TimerTask() {

            @Override
            public void run() {
                i--;
                Message message = mHandler.obtainMessage();
                message.arg1 = i;
                mHandler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000);
    }

    public void stopTime(){
        timer.cancel();
    }
    /**
     * 验证是否是手机号码
     *
     * @param str
     * @return
     */
    public static boolean isMobile(String str) {
        Pattern pattern = Pattern.compile("1[0-9]{10}");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }
}
